import { Menu, app } from "electron";
import isDev from "electron-is-dev";
import { resolve } from "path";
import _ from "lodash";
import Window from "./window.ts";
import {electronLogger} from "../vendor/electron-logger.ts";
import { APP_NAME_ZH } from "../type/const.ts";
import {electronStore} from "../vendor/electron-store.ts";



export default class MainWindow extends Window {
  url = isDev ? "http://localhost:5173/" : "./web/index.html";

  constructor() {
    super({
      width: 800,
      minWidth: 800,
      height: 680,
      minHeight: 680,
      show: false,
      frame: true,
      title: APP_NAME_ZH,
      webPreferences: {
        preload: resolve(__dirname, "./preload.js"),
      },
    });

  }

  closeMainWindow = () => {
    app.quit();
  };

  init(): void {
    electronLogger.info("init MainWindow");
    if (this.window) {
      this.showWindow()
      return;
    }

    Menu.setApplicationMenu(null);

    this.window = this.create();

    // if (isDev) {
      this.window.webContents.openDevTools()
    // }

    const mainBounds = electronStore.get("mainBounds");
    if (mainBounds) {
      this.window.setBounds(mainBounds);
    }

    // Handle current window resize
    this.window.on("resized", this.handleResize);
    this.window.on("close", this.closeMainWindow);
    // 阻止标题随页面更新
    this.window.on('page-title-updated', (event) => {
      event.preventDefault(); // 阻止标题更新
    });
    if (isDev){
      this.window.loadURL(this.url);
    } else {
      this.window.loadFile(this.url);
    }
    this.showWindow()
  }

  handleResize = () => {
    if (!this.window) return;
    const bounds = this.window.getBounds();
    electronStore.set("mainBounds", _.omit(bounds, ["x", "y"]));
  };

  showWindow() {
    if (!this.window) {
      this.init()
      return;
    }
    if (!this.window) return;

    if (this.window.isMinimized()) {
      this.window.restore();
    }
    if (this.window.isVisible()) {
      this.window.focus();
    } else {
      this.window.show();
    }
  }
}

export const mainWindow = new MainWindow();
